import 'package:flutter/material.dart';

/// Dart模式匹配示例
class PatternMatchingExample extends StatefulWidget {
  const PatternMatchingExample({super.key});

  @override
  State<PatternMatchingExample> createState() => _PatternMatchingExampleState();
}

class _PatternMatchingExampleState extends State<PatternMatchingExample> {
  String result = '点击下方按钮查看模式匹配示例';

  void _demonstrateSwitchExpression() {
    String getColorName(int colorCode) {
      return switch (colorCode) {
        1 => '红色',
        2 => '绿色',
        3 => '蓝色',
        _ => '未知颜色',
      };
    }

    setState(() {
      result =
          '''
【Switch表达式演示】
现代的switch表达式可以直接返回值：

colorCode = 1 → ${getColorName(1)}
colorCode = 2 → ${getColorName(2)}
colorCode = 3 → ${getColorName(3)}
colorCode = 99 → ${getColorName(99)}

代码示例：
String getColorName(int code) {
  return switch (code) {
    1 => '红色',
    2 => '绿色',
    3 => '蓝色',
    _ => '未知颜色',
  };
}
      ''';
    });
  }

  void _demonstrateRecordPattern() {
    // Record类型 (Dart 3.0+)
    (int, String) getPersonInfo() {
      return (25, 'Alice');
    }

    var (age, name) = getPersonInfo(); // 解构赋值

    setState(() {
      result =
          '''
【Record解构演示】
Record是Dart 3.0引入的新类型，可以返回多个值：

(int, String) getPersonInfo() {
  return (25, 'Alice');
}

// 解构赋值
var (age, name) = getPersonInfo();

结果:
  年龄: $age
  姓名: $name
      ''';
    });
  }

  void _demonstrateListPattern() {
    void analyzeList(List<int> numbers) {
      switch (numbers) {
        case []:
          setState(() {
            result = '【列表模式匹配】\n空列表';
          });
        case [var only]:
          setState(() {
            result = '【列表模式匹配】\n只有一个元素: $only';
          });
        case [var first, var second]:
          setState(() {
            result = '【列表模式匹配】\n有两个元素: $first 和 $second';
          });
        case [var first, ...var rest]:
          setState(() {
            result = '【列表模式匹配】\n第一个元素: $first\n剩余元素: $rest';
          });
      }
    }

    analyzeList([1, 2, 3, 4, 5]);
  }

  void _demonstrateObjectPattern() {
    // 使用外部定义的Point类
    String describePoint(_Point point) {
      return switch (point) {
        _Point(x: 0, y: 0) => '原点',
        _Point(x: 0, y: var y) => '在Y轴上，y=$y',
        _Point(x: var x, y: 0) => '在X轴上，x=$x',
        _Point(x: var x, y: var y) => '坐标点 ($x, $y)',
      };
    }

    setState(() {
      result =
          '''
【对象模式匹配】
可以对对象的属性进行模式匹配：

Point(0, 0) → ${describePoint(const _Point(0, 0))}
Point(0, 5) → ${describePoint(const _Point(0, 5))}
Point(3, 0) → ${describePoint(const _Point(3, 0))}
Point(3, 5) → ${describePoint(const _Point(3, 5))}

代码示例：
String describePoint(Point point) {
  return switch (point) {
    Point(x: 0, y: 0) => '原点',
    Point(x: 0, y: var y) => '在Y轴',
    Point(x: var x, y: 0) => '在X轴',
    Point(x: var x, y: var y) => '坐标点',
  };
}
      ''';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 模式匹配'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.purple.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('🎯 模式匹配概述', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text(
                      'Dart 3.0引入了强大的模式匹配功能：\n'
                      '• Switch表达式：可以直接返回值\n'
                      '• Record解构：多值返回和解构赋值\n'
                      '• 列表模式：匹配列表结构\n'
                      '• 对象模式：匹配对象属性',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 代码示例区域
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
              child: const Text('''// Switch表达式
var color = switch (code) {
  1 => 'red',
  2 => 'green',
  _ => 'unknown',
};

// Record解构
var (x, y) = getCoordinates();

// 列表模式匹配
switch (list) {
  case []:
    print('空列表');
  case [var first, ...var rest]:
    print('第一个: \$first');
}

// 对象模式匹配
switch (point) {
  case Point(x: 0, y: 0):
    print('原点');
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 13)),
            ),
            const SizedBox(height: 16),

            // 交互按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _demonstrateSwitchExpression,
                  icon: const Icon(Icons.swap_horiz),
                  label: const Text('Switch表达式'),
                ),
                ElevatedButton.icon(onPressed: _demonstrateRecordPattern, icon: const Icon(Icons.dataset), label: const Text('Record解构')),
                ElevatedButton.icon(onPressed: _demonstrateListPattern, icon: const Icon(Icons.view_list), label: const Text('列表模式')),
                ElevatedButton.icon(onPressed: _demonstrateObjectPattern, icon: const Icon(Icons.category), label: const Text('对象模式')),
              ],
            ),
            const SizedBox(height: 16),

            // 结果展示区域
            Card(
              elevation: 4,
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                constraints: const BoxConstraints(minHeight: 150),
                child: Text(result, style: const TextStyle(fontSize: 14, fontFamily: 'monospace')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 辅助类定义
class _Point {
  final int x;
  final int y;
  const _Point(this.x, this.y);
}
